<template>
  <div class="admin-layout">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="220px">
        <div class="sidebar">
          <div class="logo-container">
            <img src="@/assets/logo.png" alt="Logo" class="logo">
            <h3>超级管理员</h3>
          </div>
          
          <el-menu
            :default-active="$route.path"
            class="sidebar-menu"
            background-color="#001529"
            text-color="#fff"
            active-text-color="#409EFF"
            router>
            
            <el-menu-item index="/admin/dashboard">
              <i class="el-icon-s-home"></i>
              <span>控制台</span>
            </el-menu-item>
            
            <el-menu-item index="/admin/users">
              <i class="el-icon-user"></i>
              <span>用户管理</span>
            </el-menu-item>
            
            <el-menu-item index="/admin/phones">
              <i class="el-icon-mobile-phone"></i>
              <span>手机号管理</span>
            </el-menu-item>
            
            <el-menu-item index="/admin/invite-codes">
              <i class="el-icon-key"></i>
              <span>邀请码管理</span>
            </el-menu-item>
            
            <!-- <el-menu-item index="/admin/settings">
              <i class="el-icon-setting"></i>
              <span>系统设置</span>
            </el-menu-item> -->
          </el-menu>
        </div>
      </el-aside>
      
      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header height="60px">
          <div class="header-left">
            <i class="el-icon-s-fold toggle-sidebar"></i>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/admin/dashboard' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>{{ $route.meta.title || '管理面板' }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          
          <div class="header-right">
            <el-dropdown trigger="click">
              <span class="user-dropdown">
                <el-avatar size="small" :src="adminInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                <span class="username">{{ adminInfo.nickname || '超级管理员' }}</span>
                <i class="el-icon-arrow-down"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="showEditProfile">个人信息</el-dropdown-item>
                <!-- <el-dropdown-item>修改密码</el-dropdown-item> -->
                <el-dropdown-item divided @click.native="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 内容区 - 渲染子路由组件 -->
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加个人信息编辑对话框 -->
    <el-dialog
      title="个人信息"
      :visible.sync="profileDialogVisible"
      width="400px"
    >
      <el-form
        ref="profileForm"
        :model="profileForm"
        :rules="profileRules"
        label-width="80px"
      >
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="/api/sys/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
          >
            <div class="avatar-wrapper">
              <el-avatar
                :size="90"
                :src="profileForm.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
              ></el-avatar>
              <div class="avatar-mask">
                <i class="el-icon-camera"></i>
                <span>点击修改头像</span>
              </div>
            </div>
          </el-upload>
        </div>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="profileForm.phone" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="profileDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitProfile" :loading="submitting">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from '@/utils/http';

export default {
  name: 'AdminLayout',
  data() {
    return {
      adminInfo: JSON.parse(localStorage.getItem('user') || '{}'),
      profileDialogVisible: false,
      profileForm: {
        nickname: '',
        phone: '',
        email: '',
        avatar: ''
      },
      profileRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      submitting: false,
      uploadHeaders: {
        Authorization: localStorage.getItem('token') || ''
      }
    }
  },
  methods: {
    // 退出登录
    handleLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除token和用户信息
        localStorage.removeItem('token');
        localStorage.removeItem('userType');
        localStorage.removeItem('role');
        localStorage.removeItem('user');
        
        // 跳转到登录页
        this.$router.push('/login');
        this.$message.success('已退出登录');
      }).catch(() => {
        // 取消操作
      });
    },
    getInfo() {
      httpInstance({
        url: '/api/user/info',
        method: 'post'
      }).then(res => {
        console.log('获取用户信息:', res);
        if (res.code === 200) {
          this.adminInfo = res.data;
          localStorage.setItem('user', JSON.stringify(res.data));
        } else {
          this.$message.error(res.msg || '获取用户信息失败');
        }
        
      }).catch(err => {
        console.error('获取用户信息失败:', err);
        this.$message.error('获取用户信息失败');
      });
    },
    // 显示编辑个人信息对话框
    showEditProfile() {
      this.profileForm = {
        ...this.adminInfo,
        phone: this.adminInfo.phone || ''
      };
      this.profileDialogVisible = true;
    },
    // 头像上传前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 头像上传成功的回调
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.profileForm.avatar = res.data;
        this.$message.success('头像上传成功');
      } else {
        this.$message.error(res.msg || '头像上传失败');
      }
    },
    // 提交个人信息
    async submitProfile() {
      try {
        await this.$refs.profileForm.validate();
        this.submitting = true;

        const updateData = {
          id:this.adminInfo.id,
          nickname: this.profileForm.nickname,
          email: this.profileForm.email,
          avatar: this.profileForm.avatar
        };

        const res = await httpInstance.post('/api/user/update', updateData);
        
        if (res.code === 200) {
          this.$message.success('个人信息更新成功');
          
          this.adminInfo = { 
            ...this.adminInfo,
            ...updateData
          };
          localStorage.setItem('user', JSON.stringify(this.adminInfo));
          
          this.profileDialogVisible = false;
        } else {
          this.$message.error(res.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新个人信息失败:', error);
        this.$message.error('更新失败');
      } finally {
        this.submitting = false;
      }
    }
  },
  created() {
    // 检查token和role
    const token = localStorage.getItem('token');
    const role = localStorage.getItem('role');
    
    if (!token || role !== '3') {
      this.$message.error('无权限访问，请使用超级管理员账号登录');
      this.$router.push('/login');
      return;
    }
    
    // 如果当前路径是/admin，重定向到管理面板
    if (this.$route.path === '/admin') {
      this.$router.push('/admin/dashboard');
    }
  },
  mounted() {
    // 获取用户信息
    this.getInfo();
  }
}
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  height: 100%;
  background-color: #001529;
  color: white;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #002140;
}

.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

/* 顶部导航样式 */
.el-header {
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-sidebar {
  font-size: 20px;
  margin-right: 20px;
  cursor: pointer;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
}

/* 主内容区样式 */
.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

/* 确保容器可以滚动 */
.el-container {
  height: 100vh;
  overflow: hidden;
}

.el-container .el-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.avatar-container {
  text-align: center;
  margin-bottom: 30px;
  padding-top: 10px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-mask i {
  font-size: 24px;
  margin-bottom: 5px;
}

.avatar-mask span {
  font-size: 12px;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.el-avatar {
  display: block;
}

/* 调整表单样式 */
.el-form {
  padding: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #EBEEF5;
}
</style>